package com.antdant.service;

import com.antdant.entity.Certificate;
import com.antdant.repository.CertificateRepository;
import com.antdant.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lee Yunc
 * @Date 2021/3/17 17:03
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class CertificateService {

    @Resource
    private CertificateRepository certificateRepository;

    @Resource
    private RankService rankService;

    /**
     * 用户查询自己的证书情况
     *
     * @param certificate
     * @return
     */
    public Certificate getCertificate(Certificate certificate) {
        return certificateRepository.findByNameAndNumber(certificate.getName(), certificate.getNumber());
    }

    /**
     * 分页查询所有证书信息
     *
     * @param current
     * @param size
     * @param certificate
     * @return
     */
    public Page<Certificate> getAllCertificates(Integer current, Integer size, Certificate certificate) {
        Pageable pageable = PageRequest.of(current - 1, size);
        return certificateRepository.findAll(new Specification<Certificate>() {
            @Override
            public Predicate toPredicate(Root<Certificate> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (certificate.getRankCode() != 0) {
                    list.add(criteriaBuilder.equal(root.get("rankCode"), certificate.getRankCode()));
                }
                if (DataUtils.isNotEmptyStr(certificate.getName())) {
                    list.add(criteriaBuilder.equal(root.get("name"), certificate.getName()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    /**
     * 根据id删除证书
     *
     * @param certificateId
     * @return
     */
    public Boolean deleteCertificate(Integer certificateId) {
        try {
            certificateRepository.deleteById(certificateId);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }

    /**
     * 添加新证书
     *
     * @param certificate
     * @return
     */
    public Certificate addNewCertificate(Certificate certificate) {
        Integer rankCode = rankService.getRankCodeByGrade(certificate.getGrade());
        certificate.setRankCode(rankCode);
        return certificateRepository.saveAndFlush(certificate);
    }
}
